<template>
	<view class="page-cont">
		<navbar title="能耗"></navbar>
		<view class="main-cont" :style="{height: pageHeight}">
			<!-- 项目切换 -->
			<view class="device-select" @click="handleOpen">
				<view class="device-name">{{projectName}}</view>
				<image class="device-arrow" :src="isOpen ? '/static/up_black.png' : '/static/down_black.png'"></image>
			</view>
			<!-- 统计数据 -->
			<view class="stat-cont">
				<view class="stat-item">
					<view class="stat-item-name">当月总耗电量</view>
					<view class="stat-item-value">{{statData.pw}}<text class="stat-item-unit">kw/h</text></view>
				</view>
				<view class="stat-item">
					<view class="stat-item-name">当月总电费</view>
					<view class="stat-item-value">{{statData.pr}}<text class="stat-item-unit">元</text></view>.
				</view>
				<view class="stat-item">
					<view class="stat-item-name">节能率</view>
					<view class="stat-item-value">{{statData.jn}}<text class="stat-item-unit">%</text></view>
				</view>
			</view>
			<!-- 功能按钮 -->
			<view class="btn-cont">
				<view class="btn-item" @tap="toMonitor()">
					<text class="btn-item-name">能耗监测</text>
				</view>
				<view class="btn-item" @tap="toCheck()">
					<text class="btn-item-name">能耗查看</text>
				</view>
			</view>
			<!-- tab -->
			<tab :tabActive="currentIndex" :tabs="tabs" @tabChange="handleTabChange"></tab>

			<view class="chart-cont">
				<view v-show="currentIndex === 0">
					<trend :keys="energy.GartherType.dwpfmdf" :projectId="projectId" ref="pwItem" />
				</view>
				<view v-show="currentIndex === 1">
					<trend :keys="energy.GartherType.xmznh" :projectId="projectId" ref="prItem" />
				</view>
			</view>
		</view>
		<!-- 项目选择-->
		<uni-popup ref="popup" type="bottom" background-color="#fff" @maskClick="isOpen = false">
			<scroll-view class="popup-cont" scroll-y>
				<view class="popup-header">请选择</view>
				<view class="popup-title" v-for="(item, index) in projectList" :key="index"
					@click="handleDeviceChange(item)">{{item.name}}</view>
			</scroll-view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
	import { onShow, onLoad } from "@dcloudio/uni-app";
	import { useNavbar } from "@/utils/hooks.js";
	import * as energy from "@/api/energy.ts";
	import trend from '@/pages/energy/trend.vue';
	import useHomeStore from '@/store/home';
	import { storeToRefs } from 'pinia';
	const homeStore = useHomeStore();
	// const { projectId, projectName, projectType, deviceList } = storeToRefs(homeStore);

	onLoad((query) => {
		if (query?.projectName != undefined) {
			projectName.value = query?.projectName;
		}else{
			projectName.value = homeStore.projectName;
		};
	})

	const { proxy } = getCurrentInstance();
	const { pageHeight } = useNavbar();
	const isOpen = ref(false)
	const popup = ref()
	const projectName = ref<string>()
	const projectId = ref<number>()
	const projectList = ref([])

	/* 电费趋势 */
	const pwItem = ref();
	/* 电费趋势 */
	const prItem = ref();

	watch(projectId, (newValue, oldValue) => {
		console.log(`projectId 从 ${oldValue} 变为 ${newValue}`);
		setTimeout(() => {
			pwItem.value.getChartInfo();
			prItem.value.getChartInfo();
		}, 300)
	});

	const timeActive = ref(0)
	const timeList = ref([{ name: '小时', value: 0 }, { name: '日报', value: 1 }, { name: '月报', value: 2 }, { name: '年报', value: 3 }])

	// 项目切换
	const handleDeviceChange = (e) => {
		isOpen.value = false;
		popup.value.close();
		projectName.value = e.name;
		projectId.value = e.id;
		getStatisData();
	}

	const handleOpen = () => {
		isOpen.value = true;
		popup.value.open();
	}

	const statData = ref({
		pw: "-",
		pr: "-",
		jn: "-"
	})

	const currentIndex = ref(0)
	const tabs = ref(["电费统计", "耗能统计"]);
	const handleTabChange = (e) => {
		currentIndex.value = e;
		if (e == 0) {
			pwItem.value.getChartInfo();
		} else {
			prItem.value.getChartInfo();
		}
	}

	const toMonitor = () => {
		uni.navigateTo({ url: `/pages/energy/monitor?projectId=${projectId.value}` })
	}

	const toCheck = () => {
		uni.navigateTo({ url: `/pages/energy/check?projectId=${projectId.value}` })
	}


	onMounted(() => {
		getInfo()
	})

	const getInfo = async () => {
		//获取项目信息
		const projectResult = await energy.getUserProject({})
		projectList.value.push(...projectResult.data)
		if (projectList.value.length > 0) {
			// index 跳转 默认选中携带项目名称 
			if (projectName.value != undefined && projectId.value == undefined) {
				for (var i = 0; i < projectList.value.length; i++) {
					if (projectName.value == projectList.value[i].name) {
						projectId.value = projectList.value[i].id;
						break;
					}
				}
			}
			if (projectId.value == undefined) {
				projectName.value = projectList.value[0].name;
				projectId.value = projectList.value[0].id;
			}

			//获取统计数据
			getStatisData();

		} else {
			uni.showToast({
				title: '暂无项目信息',
				icon: 'none'
			})
			uni.navigateBack({ delta: 1 })
		}
	}

	const getStatisData = async () => {
		// 总电量 电费 求和
		let keys = ["0_0_" + projectId.value + "_pw", "0_0_" + projectId.value + "_pr"]
		const dataResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs().format('YYYY-MM'), "endTime": proxy.dayjs().format('YYYY-MM'),
			"format": energy.FormatType.month, "oper": energy.OperType.sum, "keys": keys
		})
		getStatisInfo(dataResult);
		// 节能率 取平均值
		const jnDataResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs().format('YYYY-MM'), "endTime": proxy.dayjs().format('YYYY-MM'),
			"format": energy.FormatType.month, "oper": energy.OperType.avg, "keys": "0_0_" + projectId.value + "_jn"
		})
		getStatisInfo(jnDataResult);
	}

	const getStatisInfo = (dataResult) => {
		Object.keys(dataResult).forEach(key => {
			if (key.includes("pw")) {
				//电量
				statData.value.pw = dataResult[key].length > 0 ? formatDecimal(dataResult[key][0].value) : "-"
			} else if (key.includes("pr")) {
				//电费
				statData.value.pr = dataResult[key].length > 0 ? formatDecimal(dataResult[key][0].value) : "-"
			} else if (key.includes("jn")) {
				//节能率
				statData.value.jn = dataResult[key].length > 0 ? formatDecimal(dataResult[key][0].value) : "-"
			}
		});
	}


	function formatDecimal(num) {
		return parseFloat(num.toFixed(2)).toString();
	}
</script>

<style lang="scss" scoped>
	.page-cont {
		display: flex;
		flex-direction: column;
		height: 100%;
		width: 100%;

		.device-select {
			height: 80rpx;
			line-height: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: transparent;
			border-bottom: 1px solid #ccc;

			.device-name {
				color: #666;
				font-size: 28rpx;
			}

			.device-arrow {
				padding-left: 10rpx;
				width: 32rpx;
				height: 32rpx;
			}
		}

		.stat-cont {
			margin-left: 25rpx;
			margin-right: 25rpx;
			margin-top: 25rpx;
			padding: 20rpx 30rpx;
			display: flex;
			border-radius: 10rpx;
			background: linear-gradient(135deg, rgba(126, 156, 255, 1) 0%, rgba(29, 74, 218, 1) 100%),
				linear-gradient(180deg, rgba(238, 240, 249, 1) 0%, rgba(255, 255, 255, 1) 100%);
			box-sizing: border-box;

			.stat-item {
				flex: 1;

			}

			.stat-item-name,
			.stat-item-value,
			.stat-item-unit {
				color: #fff;
				font-size: 25rpx;
			}

			.stat-item-value {
				padding-top: 24rpx;
				font-size: 25rpx;
				font-weight: 600;
			}

			.stat-item-unit {
				padding-left: 10rpx;
				font-size: 23rpx;
				font-weight: 400;
			}
		}

		.btn-cont {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			margin-left: 16vw;
			margin-right: 16vw;
			margin-top: 50rpx;
			margin-bottom: 50rpx;

			.btn-item {
				display: flex;
				flex-direction: row;
				border-radius: 10rpx;
				width: 200rpx;
				padding-top: 25rpx;
				padding-bottom: 25rpx;
				justify-content: center;
				border: 2rpx solid #FFFFFF;
				box-shadow: 0px 10px 20px 0px rgba(95, 131, 249, 0.1);
				background: linear-gradient(180deg, rgba(255, 255, 255, 1) 0%, rgba(238, 240, 249, 1) 100%);

				.btn-item-name {
					color: #333333;
					font-size: 25rpx;
				}
			}

		}

		.chart-cont {
			display: flex;
			flex-direction: column;
			margin-right: 25rpx;
			margin-left: 25rpx;
			margin-top: 40rpx;
			margin-bottom: 40rpx;
			border-radius: 10rpx;
			background-color: #FAFAFC;
			border: 2rpx solid #FFFFFF;
			padding: 25rpx;
			box-shadow: 0rpx 10rpx 10rpx 0rpx rgba(135, 166, 233, 0.1);

			.chart-cont-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 600;
			}

			.chart-cont-time-tab {
				margin-top: 30rpx;
				display: flex;

				.chart-cont-time-tab-item,
				.chart-cont-time-tab-active {
					margin-left: 30rpx;
					height: 60rpx;
					line-height: 60rpx;
					flex: 1;
					color: #5A6570;
					font-size: 22rpx;
					text-align: center;
					border-radius: 5rpx;
					border: 1px solid #ccc;
					background-color: #fff;

					&:first-child {
						margin-left: 0;
					}
				}

				.chart-cont-time-tab-active {
					color: #5F83F9;
					border-color: #5F83F9;
					background-color: rgba(95, 131, 249, 0.1);
				}
			}
		}
	}

	.popup-cont {
		background: #fff;
		max-height: 80vh;
		z-index: 102;

		.popup-title,
		.popup-header {
			height: 100rpx;
			line-height: 100rpx;
			color: #333;
			font-size: 28rpx;
			text-align: center;
			border-top: 2rpx solid #eee;
		}

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
		}
	}
</style>